﻿Imports System
Imports System.Collections.Specialized
Imports System.Reflection

Namespace System.Workflow.ComponentModel.Compiler
    Friend NotInheritable Class ReferencedAssemblyResolver
        ' Methods
        Public Sub New(ByVal serviceProvider As IServiceProvider, ByVal referencedAssemblies As StringCollection, ByVal localAssembly As Assembly)
            Me.serviceProvider = serviceProvider
            Me.referencedAssemblies = referencedAssemblies
            Me.localAssembly = localAssembly
        End Sub

        Private Function ResolveAssembly(ByVal name As String) As Assembly
            If Not Me.resolving Then
                If ((Not Me.localAssembly Is Nothing) AndAlso (name = Me.localAssembly.FullName)) Then
                    Return Me.localAssembly
                End If
                Try 
                    Me.resolving = True
                    Dim thatName As New AssemblyName(name)
                    Dim str As String
                    For Each str In Me.referencedAssemblies
                        Try 
                            Dim assemblyName As AssemblyName = AssemblyName.GetAssemblyName(str)
                            If ((assemblyName Is Nothing) OrElse Not ParseHelpers.AssemblyNameEquals(assemblyName, thatName)) Then
                                [Continue] For
                            End If
                            Try 
                                Return Assembly.Load(assemblyName)
                            Catch obj1 As Object
                                Return Assembly.LoadFrom(str)
                            End Try
                        Catch obj2 As Object
                            [Continue] For
                        End Try
                    Next
                Finally
                    Me.resolving = False
                End Try
            End If
            Return Nothing
        End Function

        Public Function ResolveEventHandler(ByVal sender As Object, ByVal args As ResolveEventArgs) As Assembly
            Return Me.ResolveAssembly(args.Name)
        End Function

        Friend Sub SetLocalAssembly(ByVal localAsm As Assembly)
            Me.localAssembly = localAsm
        End Sub


        ' Fields
        Private localAssembly As Assembly
        Private referencedAssemblies As StringCollection = New StringCollection
        Private resolving As Boolean
        Private serviceProvider As IServiceProvider
    End Class
End Namespace

